package admin.gateway.component;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import reactor.core.publisher.Mono;
import admin.common.constant.AuthConstant;
import admin.common.domain.Client;
import admin.common.domain.dto.UserDto;
import admin.common.properties.IgnoreUrlsProperties;
import admin.common.properties.OauthProperties;

import java.net.URI;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 鉴权管理器，用于判断是否有资源的访问权限
 * Created by zgb on 2020/6/19.
 */
@Slf4j
@Component
public class AuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private IgnoreUrlsProperties ignoreUrlsProperties;

    @Autowired
    private OauthProperties oauthProperties;

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
        ServerHttpRequest request = authorizationContext.getExchange().getRequest();
        URI uri = request.getURI();
        PathMatcher pathMatcher = new AntPathMatcher();
        //白名单路径直接放行
        //白名单路径
        List<String> ignoreUrlList = new ArrayList<String>(ignoreUrlsProperties.getUrls());
        String[] ignoreUrlArr = ignoreUrlList.toArray(new String[ignoreUrlList.size()]);
        for (String ignoreUrl : ignoreUrlArr) {
            if (pathMatcher.match(ignoreUrl, uri.getPath())) {
                return Mono.just(new AuthorizationDecision(true));
            }
        }
        //对应跨域的预检请求直接放行
        if (request.getMethod() == HttpMethod.OPTIONS) {
            return Mono.just(new AuthorizationDecision(true));
        }
        UserDto userDto = null;
        try {
            //获取jwt负载
            String token = request.getHeaders().getFirst(AuthConstant.JWT_TOKEN_HEADER);
            if (StrUtil.isEmpty(token)) {
                return Mono.just(new AuthorizationDecision(false));
            }
            String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, "");
            JWSObject jwsObject = JWSObject.parse(realToken);
            String userStr = jwsObject.getPayload().toString();
            userDto = JSONUtil.toBean(userStr, UserDto.class);
        } catch (ParseException e) {
            e.printStackTrace();
            return Mono.just(new AuthorizationDecision(false));
        }
        String currentClientId = userDto.getClientId();
        List<Client> clients = oauthProperties.getClients();
        Client currentClient = clients.stream().filter(e -> e.getId().equals(currentClientId)).findFirst().orElse(null);
        //不同用户体系登录不允许互相访问
        if (!pathMatcher.match(currentClient.getUrlPattern(), uri.getPath())) {
            return Mono.just(new AuthorizationDecision(false));
        }
        if (currentClient.getPermissionValidYn()) {
            //管理端路径需校验权限
            Map<Object, Object> resourceRolesMap = redisTemplate.opsForHash().entries(AuthConstant.RESOURCE_ROLES_MAP_KEY);
            Iterator<Object> iterator = resourceRolesMap.keySet().iterator();
            List<String> authorities = new ArrayList<>();
            while (iterator.hasNext()) {
                String pattern = (String) iterator.next();
                String concat = request.getMethod().name().concat(":").concat(uri.getPath());
                //String concat = uri.getPath();
                if (pathMatcher.match(pattern, concat)) {
                    //找出当前url匹配的权限表达式:roleId_roleName
                    authorities.addAll(Convert.toList(String.class, resourceRolesMap.get(pattern)));
                }
            }
            authorities = authorities.stream().map(i -> i = AuthConstant.AUTHORITY_PREFIX + i).collect(Collectors.toList());
            //认证通过且角色匹配的用户可放行访问当前路径
            return mono
                    //过滤：已认证，向下执行
                    .filter(Authentication::isAuthenticated)
                    //遍历
                    .flatMapIterable(Authentication::getAuthorities)
                    //转换
                    .map(GrantedAuthority::getAuthority)
                    //过滤:令牌包含需要的角色
                    .any(authorities::contains)
                    //转换
                    .map(AuthorizationDecision::new)
                    .defaultIfEmpty(new AuthorizationDecision(false));
        }
        //放行
        return Mono.just(new AuthorizationDecision(true));
    }

}
